/**
 * Created by CM on 16/9/12.
 */
String.prototype.toChartArray = function () {
    var arr = [];
    for (var i = 0; i < this.length; i++) {
        arr.push(this.charAt(i))
    }
    return arr;
}

$(function () {
    windowInit();

    if (typeof  editCallBack != "undefined") {
        if ($(".edit_able").length > 0) {
            console.log("found click edit target elements!%o", $(".edit_able"));
        }
        $(".edit_able").clickEditVal(editCallBack)
    }

    $("img").on("error", function (index, el) {
        $(this).attr("src", ctx + "/resources/ueditor/dialogs/image/images/image.png");
    })
})

function windowInit() {
    var htmlFontSize = window.outerWidth >= 1600 ? "62.5%" : "31.25%";
    var height = window.innerHeight - 60;
    $(".content-main-frame").css("height", height + "px");
    $("html").css("font-size", htmlFontSize);
    $(window).resize(function () {
        var htmlFontSize = window.outerWidth >= 1600 ? "62.5%" : "31.25%";
        $("html").css("font-size", htmlFontSize);
        var height = window.innerHeight - 60;
        $(".content-main-frame").css("height", height + "px");
    })
}

function getJson(options) {
    console.log("[post:json] options:%o", options);
    if (isEmpty(options.url)) {
        console.error("url must be config!");
        return;
    }
    if (isEmpty(options.data)) {
        options.data = {};
    }
    $.ajax({
        url: options.url + "?" + $.param(options.data).replace(/%5D/g, "").replace(/%5B/g, ""),
        type: "post",
        dataType: "json",
        success: function (res) {
            console.log("res:%o", res);
            options.success(res);
        },
        error: function (err, sta) {
            var resTxt = err.responseText;
            if (!isEmpty(resTxt)) {
                var res = JSON.parse(resTxt);
                alert(res.msg);
            }
            console.log("请求发生错误:%o", err);
        }
    })
}

function isEmpty(obj) {
    if (obj == null || obj == undefined) {
        return true;
    }
    if (typeof obj == "object") {
        for (var i in obj) {
            if (!isEmpty(obj[i])) {
                return false;
            }
        }
        return true;
    } else if (typeof obj == "string") {
        return obj == "" || obj == undefined || obj == "null" || obj == null;
    } else if (typeof obj == "undefined" || obj == null) {
        return true;
    }
}

function getContextPath() {
    return ctx;
}

function loadingShow() {
    $(".loading-hover,.loading-img").remove();
    $("body").append("<div class=\"loading-hover\"></div>").append("<div class=\"loading-img\"><i class='fa fa-spinner fa-spin'></i></div>");
}

function loadingHide() {
    $(".loading-hover,.loading-img").remove();
}

var asyncAjax = function (opts) {
    if (isEmpty(opts)) {
        console.error("async options empty!");
        return -1;
    }
    if (isEmpty(opts.url)) {
        console.error("async options url empty!");
        return -1;
    }
    var ajaxOpts = {
        url: opts.url,
        contentType: isEmpty(opts.contentType) ? "application/x-www-form-urlencoded; charset=UTF-8" : opts.contentType,
        type: (isEmpty(opts.type) ? "post" : opts.type),
        async: true,
        data: (isEmpty(opts.data) ? {} : opts.data),
        beforeSend: function (req) {
            loadingShow();
            if (!isEmpty(opts.beforeSend) && typeof opts.beforeSend == "function") {
                opts.beforeSend(req);
            }
        },
        success: function (res) {
            if (!isEmpty(opts.success) && typeof opts.success == "function") {
                opts.success(res);
            }
            loadingHide();
        },
        error: function (e) {
            console.error(e);
            if (!isEmpty(opts.error) && typeof opts.error == "function") {
                opts.error(e);
            }
        },
        complete: function () {
            if (!isEmpty(opts.complete) && typeof opts.complete == "function") {
                opts.complete();
            }
        }
    };
    if (!isEmpty(opts.dataType)) {
        ajaxOpts["dataType"] = opts.dataType;
    }
    $.ajax(ajaxOpts);
}

$.extend({
    msgSuccess: function (msg) {
        Messenger().run({
            successMessage: msg,
            showCloseButton: true,
            action: function (opts) {
                return opts.success();
            }
        });
    },
    msgError: function (msg) {
        Messenger().run({
            errorMessage: '',
            showCloseButton: true,
            action: function (opts) {
                return opts.error();
            }
        });
    }
})

var uploadFile = function (fileInputId, prviewElementId, hideValueId, type) {
    var file = $("#" + fileInputId);
    var previewElement = $("#" + prviewElementId);
    var val = $("#" + hideValueId);
    if (file == null || file == undefined) {
        alert("文件选择元素ID无效！");
        return;
    }
    if (val == null && val == undefined) {
        alert("返回值存储元素ID无效！");
        return;
    }
    var gp = self.setInterval(function () {
        getProgress(gp);
    }, 50);
    $.ajaxFileUpload(
        {
            url: ctx + '/common/file/upload/' + type,
            type: 'post',
            dataType: 'json',
            fileElementId: fileInputId,
            async: false,
            success: function (data) {
                console.info("upload file result:%o", data);
                var proxResultStr = data["proxResult"];
                if (!isEmpty(file_upload_proxy_server) && proxResultStr && proxResultStr.indexOf('SUCCESS') != -1) {
                    data = JSON.parse(proxResultStr);
                }
                window.clearInterval(gp);
                //上传成功返回的信息｛filePath:上传文件后取得的url，result:是否成功，成功为0，失败为-x｝
                if (data.result == "0") {
                    if (previewElement != null && previewElement != undefined) {
                        previewElement.attr("src", data.url);
                    }
                    if (val != null && val != undefined) {
                        val.val(data.url.replace(/;jsessionid.*/g, ""));
                    }
                } else {
                    alert(data.msg);
                }
                if (typeof callback == "function") {
                    callback();
                }
            },
            error: function (data, status, e) {
                alert("上传失败:" + e);
                window.clearInterval(gp);
            }
        }
    )
};
var getProgress = function (intervalid) {
    $.ajax({
        url: ctx + "/common/file/upload/progress",
        async: false,
        type: "post",
        beforeSend: function () {

        },
        success: function (data) {
            if (data.result != 0) {
                return;
            }
            $(".circleProgress_wrapper ").show();
            $(".upload_progress_tip").html(data.progress != 100.00 ? data.progress + "%" : "上传成功!");
            $(".progress_text").html(data.progress.split(".")[0] + "%");
            if (data.progress <= 50) {
                var rotate = 45 + 3.6 * data.progress;
                $(".rightcircle").css("-webkit-transform", "rotate(" + rotate + "deg)");
            } else {
                $(".rightcircle").css("-webkit-transform", "rotate(225deg)");
                var rotate = 45 + (data.progress - 50) * 3.6;
                $(".leftcircle").css("-webkit-transform", "rotate(" + rotate + "deg)");
            }
            if (data.progress == 100.00) {
                window.clearInterval(intervalid);
                setTimeout(function () {
                    $(".circleProgress_wrapper").fadeOut();
                    $(".rightcircle").css("-webkit-transform", "rotate(45deg)");
                    $(".leftcircle").css("-webkit-transform", "rotate(45deg)");
                }, 500);
            }
        },
        error: function (e) {
            console.error("get file upload occur error:%o", e);
        }
    })
};

Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

function formatDate(date) {
    if (!date) {
        return '--';
    }
    var str = new Date(date).format("yyyy-MM-dd hh:mm:ss");
    return str;
}

function reSearch() {
    $("#pageNum").val("1");
    $("#total").val("0");
    loadData();
}


jQuery.fn.clickEditVal = function (editCallBack) {

    $(this).off().on("click", function () {
        var name = $(this).attr("data-name");
        var id = $(this).attr("data-id");
        var type = $(this).attr("data-type");
        type = type || "text";
        var src = $(this).text();

        if (type == "img") {
            src = $(this).attr("data-src");
        }

        var data = {
            name: name,
            id: id,
            src: src,
            type: type
        }


        var _this = $(this);

        console.log("common box append! target element:%o", _this);

        if (type == "good-class") {
            //特殊处理商品类别的编辑
            bootbox.confirm({
                message: '<div id="good-class-edit-tree" class="tree" style="max-height:20rem;overflow-y:auto;\"></div>',
                title: "修改商品类别",
                buttons: {
                    confirm: {
                        label: '确定'
                    },
                    cancel: {
                        label: '取消'
                    }
                },
                callback: function (res) {
                    if (res == true) {
                        var selectedItem = $("#good-class-edit-tree").tree("selectedItems");
                        console.log("modify result :%o", selectedItem);
                        if (isEmpty(selectedItem)) {
                            bootbox.alert("商品类型不能为空，操作失败!");
                        } else {
                            var value = {};
                            data["value"] = selectedItem[0]["name"].trim();
                            editCallBack(data, _this);


                            var temp = {
                                good_class_id: selectedItem[0]["id"] + "",
                                good_id: id
                            };
                            asyncAjax({
                                url: ctx + "/goodMgr/good/update",
                                data: JSON.stringify(temp),
                                type: "post",
                                dataType: "json",
                                contentType: "application/json;charset:UTF-8",
                                success: function (res) {
                                    console.log("update good_class id res:%o", res);
                                }
                            })
                        }
                    }
                }
            })

            asyncAjax({
                url: ctx + "/shop/good/type/data",
                type: "post",
                success: function (res) {
                    if (res.result == 0) {
                        var allClass = res.data.list;
                        var treeData = {};
                        treeData[allClass["title"]] = getClassItemData(allClass);
                        var daso = new DataSourceTree({data: treeData});
                        $('#good-class-edit-tree').admin_tree({
                            dataSource: daso,
                            multiSelect: false,
                            loadingHTML: '<div class="tree-loading"><i class="fa fa-spinner fa-2x fa-spin"></i>Loading...</div>',
                            'open-icon': 'fa-minus',
                            'close-icon': 'fa-plus',
                            'selectable': true,
                            'selected-icon': 'fa-check',
                            'unselected-icon': 'fa-times'
                        });
                        $('.tree').find('[class*="fa-"]').addClass("fa");
                    } else {
                        Messenger().run({
                            errorMessage: '请求数据发生错误:' + res.msg,
                            showCloseButton: true,
                            action: function (opts) {
                                return opts.error();
                            }
                        });
                    }
                }
            })

        } else {
            $("#edit-common-box").tmpl(data).appendTo($("body"));

            $("#edit-common-box-pop").modal("show");
            if (type == "time") {
                $("#edit-common-val").datetimepicker({
                    format: "yyyy-mm-dd hh:ii:ss",
                    autoclose: true,
                    todayBtn: true
                });
            }

            $("#edit-common-box-pop .submitBtn").one("click", function () {
                try {
                    var val = $("#edit-common-val").val();

                    if (!isEmpty(val)) {

                        data["value"] = val;

                        if (typeof editCallBack != "undefined") {
                            editCallBack(data, _this);
                        }

                    }

                } catch (e) {
                    console.error("error,%o", e);
                }

                $("#edit-common-box-pop").modal("hide").remove();

            })
        }
    })
}


$.fn.serializeJson = function () {
    var serializeObj = {};
    var array = this.serializeArray();
    var str = this.serialize();
    $(array).each(function () {
        if (serializeObj[this.name]) {
            if ($.isArray(serializeObj[this.name])) {
                serializeObj[this.name].push(this.value);
            } else {
                serializeObj[this.name] = [serializeObj[this.name], this.value];
            }
        } else {
            serializeObj[this.name] = this.value;
        }
    });
    return serializeObj;
};

